<template>
<div>
  <!-- elcfg:{{elcfg}} showAllLevels:{{showAlllevels}}
  <hr />
  optcfg:{{optcfg}}
  <hr />
  props:{{props}}
  <hr />
  {{options}}
  <hr /> -->
  <!-- value:{{value}} -->
  {{showAlllevels}}
  <el-cascader v-bind="elcfg" :show-all-levels="showAlllevels" :options="options" :props="props" v-model="v">    
  </el-cascader>  
</div>
  
</template>

<script>
// 级联下拉封装
import axios from 'axios'
export default {
  name:"myCascader",
  props:['elcfg','optcfg','props','value'],
  methods:{
    async fillOptions(){
      //todo fill options from api data or static data
      if(!this.optcfg) return
      if(this.optcfg.dynamicOption){
        if(!this.optcfg.dynamicOptionApi) return
        
        var opt=JSON.parse(this.optcfg.dynamicOptionApi)
        var method=opt.method
        var url=opt.url
        if(method=='GET'){
          try{
            var rep=await axios.get(url)
            var data=rep.data[this.optcfg.apiReturnField]          
            this.genOpt(this.optcfg.optionType,data)
          }
          catch{}
        }
        else{
          var rep=await axios.post(url)
          var data=rep.data[this.optcfg.apiReturnField]
          this.genOpt(this.optcfg.optionType,data)
        }
      }
      else{        
        if(this.optcfg.staticOptions){
          // console.log(this.optcfg.staticOptions);
          this.genOpt(this.optcfg.optionType,JSON.parse(this.optcfg.staticOptions))
        }
      }
      // console.log(this.optcfg);
    },
    genOpt(type,json){
      // console.log(json);
      if(type=='tree'){
        this.options=json
      }
      else if (type=='list'){
        this.genTreeFromList(json)
      }
    },
    genTreeFromList(list){
      var idField=this.optcfg.optionIdField
      var pidField=this.optcfg.optionPidField
      var roots=list.filter(x=>x[pidField]==0)
      roots.forEach(element => {
        this.fillChildren(idField,pidField,element,list)
      });
      // console.log(roots);
      this.options=roots
      // console.log(roots);
      // console.log('gen tree from list',list);
    },
    fillChildren(idField,pidField,node,all){
      // console.log(node);
      var eles=all.filter(x=>x[pidField]==node[idField])
      var childrenField=this.optcfg.optionChildField
      if(!childrenField) childrenField='children'
      if(eles.length>0){
        node[childrenField]=eles
        eles.forEach(e=>{
          this.fillChildren(idField,pidField,e,all)
        })
      }
      // console.log(eles);
    }
  },
  watch:{
    optcfg:{
      immediate:true,
      deep:true,
      async handler(n,o){
        await this.fillOptions()        
      }
    },
    'elcfg.showAllLevels':{
      immediate:true,
      handler(n,o){
        this.showAlllevels=n
      }
    },
    v(){
      this.$emit('input',this.v)
    }
  },
  data(){
    return {
      v:"",
      showAlllevels:true,
      options:[]
      
    }
  }
}
</script>

<style>

</style>